package com.quectel.core.module.securitypatrol.service.impl;


import cn.hutool.core.lang.func.LambdaUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.quectel.constant.core.securitypatrol.SecurityPatrolEventReportConstants;
import com.quectel.constant.core.securitypatrol.SecurityPatrolTaskConstants;
import com.quectel.constant.global.SystemConstants;
import com.quectel.core.constants.RedisCacheConstants;
import com.quectel.core.module.dept.service.DeptPersonService;
import com.quectel.core.module.device.dto.DeviceDto;
import com.quectel.core.module.device.service.DeviceService;
import com.quectel.core.module.securitypatrol.dao.SecurityPatrolEventReportDao;
import com.quectel.core.module.securitypatrol.dto.SecurityPatrolEventReportDto;
import com.quectel.core.module.securitypatrol.dto.SecurityPatrolTaskDto;
import com.quectel.core.module.securitypatrol.dto.SecurityPatrolTaskRouteDto;
import com.quectel.core.module.securitypatrol.entity.SecurityPatrolEventReportEntity;
import com.quectel.core.module.securitypatrol.service.SecurityPatrolEventReportService;
import com.quectel.core.module.securitypatrol.service.SecurityPatrolSubjectService;
import com.quectel.core.module.securitypatrol.service.SecurityPatrolTaskRouteService;
import com.quectel.core.module.securitypatrol.service.SecurityPatrolTaskService;
import com.quectel.core.module.village.service.VillageService;
import com.quectel.core.module.workorder.dto.WorkOrderLogDto;
import com.quectel.core.module.workorder.service.WorkOrderLogService;
import com.quectel.core.module.workorder.service.WorkOrderService;
import com.quectel.util.common.CopyUtils;
import com.quectel.util.common.JacksonUtils;
import com.quectel.util.kit.CacheKit;
import com.quectel.util.kit.Snowflake;
import com.quectel.util.mybatis.MyBatisPlusUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.function.Function;

/**
 * @author caolu
 * @email louis.cao@quectel.com
 * @date 2022/05/07 14:10
 */
@DubboService
public class SecurityPatrolEventReportServiceImpl extends ServiceImpl<SecurityPatrolEventReportDao, SecurityPatrolEventReportEntity> implements SecurityPatrolEventReportService {

    private static final Logger LOGGER = LoggerFactory.getLogger(SecurityPatrolEventReportServiceImpl.class);

    /**
     * 入参解释:实体id
     */
    private static final Function<Long, String> SECURITY_PATROL_EVENT_REPORT_CACHE_BY_ID_FUNC = id -> String.format(RedisCacheConstants.PROJECT_NAME + "SECURITY_PATROL_EVENT_REPORT_CACHE_BY_ID:%d", id);

    @Autowired
    private SecurityPatrolEventReportDao securityPatrolEventReportDao;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private SecurityPatrolSubjectService securityPatrolSubjectService;
    @Autowired
    private WorkOrderService workOrderService;
    @Autowired
    private WorkOrderLogService workOrderLogService;
    @Autowired
    private DeptPersonService deptPersonService;
    @Autowired
    private SecurityPatrolTaskRouteService taskRouteService;
    @Autowired
    private SecurityPatrolTaskService securityPatrolTaskService;
    @Autowired
    private SecurityPatrolTaskRouteService securityPatrolTaskRouteService;
    @Autowired
    private VillageService villageService;

    /**
     * query List 不填充
     *
     * @param params
     * @return
     */
    @Override
    public List<SecurityPatrolEventReportDto> queryListWithoutPadding(Map<String, Object> params) {
        List<SecurityPatrolEventReportEntity> list = securityPatrolEventReportDao.queryList(params);
        List<SecurityPatrolEventReportDto> result = CopyUtils.copyList(list, SecurityPatrolEventReportDto.class);
        return result;
    }

    /**
     * 移动端 上报 点位 和 记录信息
     *
     * @param securityPatrolTaskRouteDto
     * @param eventReportDtoList
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void report(SecurityPatrolTaskRouteDto securityPatrolTaskRouteDto,
                       List<SecurityPatrolEventReportDto> eventReportDtoList) {

        SecurityPatrolTaskDto securityPatrolTaskDto = securityPatrolTaskService.selectById(securityPatrolTaskRouteDto.getTaskId());

        Set<Byte> reportStatusSet = new HashSet<>();

        // 异常正常传-1 ,后端判断
        // 不是跳检 那么上报list的状态set处理下 有异常就是异常，否则就正常 往 点位task route 上更新下。
        // 不满足条件那么传入的应该是status == 2 跳检。直接保存
        if (SecurityPatrolEventReportConstants.ReportStatusEnum.NOT_CHANGED.getStatus().equals(securityPatrolTaskRouteDto.getStatus())
                && !securityPatrolTaskRouteDto.getStatus().equals(SecurityPatrolEventReportConstants.ReportStatusEnum.STATUS_SKIP_INSPECTION.getStatus())) {

            // 修改report list
            for (SecurityPatrolEventReportDto reportDto : eventReportDtoList) {
                reportStatusSet.add(reportDto.getStatus());
                reportDto.setCompleteTime(new Date());
                updateById(reportDto);
            }

            // 上报的状态非空
            if (!reportStatusSet.isEmpty()) {
                if (reportStatusSet.contains(SecurityPatrolEventReportConstants.ReportStatusEnum.STATUS_ABNORMAL.getStatus())) {
                    securityPatrolTaskRouteDto.setStatus(SecurityPatrolEventReportConstants.ReportStatusEnum.STATUS_ABNORMAL.getStatus());
                } else {
                    securityPatrolTaskRouteDto.setStatus(SecurityPatrolEventReportConstants.ReportStatusEnum.STATUS_NORMAL.getStatus());
                }
            }
        }

        // 跳检处理 上报点位只有跳检才传status=2
        if (SecurityPatrolEventReportConstants.ReportStatusEnum.STATUS_SKIP_INSPECTION.getStatus().equals(securityPatrolTaskRouteDto.getStatus())) {
            reportStatusSet.add(SecurityPatrolEventReportConstants.ReportStatusEnum.STATUS_SKIP_INSPECTION.getStatus());
            //根据点位id 查询生成的上报list 更新状态为跳检
            Map<String, Object> queryMap = new HashMap<>();
            queryMap.put(LambdaUtil.getFieldName(SecurityPatrolEventReportDto::getTaskRouteId), securityPatrolTaskRouteDto.getId());
            List<SecurityPatrolEventReportDto> reportDtoList = queryList(queryMap);
            if (reportDtoList.size() > 0) {
                for (int i = 0; i < reportDtoList.size(); i++) {
                    SecurityPatrolEventReportDto reportDto = reportDtoList.get(i);
                    reportDto.setSnapshotImg(securityPatrolTaskRouteDto.getSnapshotImg());
                    reportDto.setDetail(securityPatrolTaskRouteDto.getDetail());
                    reportDto.setStatus(SecurityPatrolEventReportConstants.ReportStatusEnum.STATUS_SKIP_INSPECTION.getStatus());
                    reportDto.setAssignWorkOrder(SecurityPatrolEventReportConstants.AssignWorkOrderStatusEnum.NO_ASSIGN_WORK_ORDER.getStatus());
                    reportDto.setCompleteTime(new Date());
                    updateById(reportDto);
                }
            }

        }

        // 更新 task router 状态
        securityPatrolTaskRouteDto.setCompleteTime(new Date());
        securityPatrolTaskRouteService.updateById(securityPatrolTaskRouteDto);

        // 填充 routeExecTotalStatus  根据taskId 查询出 taskRouter list .处理状态
        Map<String, Object> queryMap = new HashMap<>();
        queryMap.put(LambdaUtil.getFieldName(SecurityPatrolTaskRouteDto::getTaskId), securityPatrolTaskDto.getId());
        List<SecurityPatrolTaskRouteDto> securityPatrolTaskRouteDtos = securityPatrolTaskRouteService.queryList(queryMap);

        Set<Byte> taskRouteStatusSet = new HashSet<>();
        for (SecurityPatrolTaskRouteDto taskRouteDto : securityPatrolTaskRouteDtos) {
            taskRouteStatusSet.add(taskRouteDto.getStatus());
        }

        // 任务上的状态 [] 状态set有异常, 跳检 ，漏检 。那么去掉正常和-1的状态
        if (taskRouteStatusSet.contains(SecurityPatrolEventReportConstants.ReportStatusEnum.STATUS_ABNORMAL.getStatus())
                || taskRouteStatusSet.contains(SecurityPatrolEventReportConstants.ReportStatusEnum.STATUS_SKIP_INSPECTION.getStatus())
                || taskRouteStatusSet.contains(SecurityPatrolEventReportConstants.ReportStatusEnum.MISSED_DETECTION.getStatus())) {
            taskRouteStatusSet.remove(SecurityPatrolEventReportConstants.ReportStatusEnum.STATUS_NORMAL.getStatus());
            taskRouteStatusSet.remove(SecurityPatrolEventReportConstants.ReportStatusEnum.NOT_CHANGED.getStatus());
        }

        //更新 routeExecTotalStatus
        securityPatrolTaskDto.setRouteExecTotalStatus(JacksonUtils.toJsonString(taskRouteStatusSet));
        //更新执行数量
        Integer execCount = securityPatrolTaskDto.getExecCount();
        securityPatrolTaskDto.setExecCount(++execCount);
        if (securityPatrolTaskDto.getExecCount() < securityPatrolTaskDto.getRouteCount()) {
            securityPatrolTaskDto.setExecStatus(SecurityPatrolTaskConstants.TasksStatusEnum.STATUS_EXECUTING.getStatus());
        }
        if (securityPatrolTaskDto.getExecCount().equals(securityPatrolTaskDto.getRouteCount())) {
            securityPatrolTaskDto.setExecStatus(SecurityPatrolTaskConstants.TasksStatusEnum.STATUS_EXECUTED.getStatus());
            securityPatrolTaskDto.setCompleteTime(new Date());
        }
        securityPatrolTaskService.updateById(securityPatrolTaskDto);
    }

    /**
     * 批量保存上报记录
     *
     * @param eventReportDtoList
     */
    @Override
    public void batchSave(List<SecurityPatrolEventReportDto> eventReportDtoList) {
        List<SecurityPatrolEventReportEntity> eventReportEntities = CopyUtils.copyList(eventReportDtoList, SecurityPatrolEventReportEntity.class);
        for (SecurityPatrolEventReportEntity eventReportEntity : eventReportEntities) {
            eventReportEntity.setId(Snowflake.nextId());
        }
        super.saveBatch(eventReportEntities);
    }

    @Override
    public SecurityPatrolEventReportDto selectOne(Long taskRouteId, Long subjectId) {
        SecurityPatrolEventReportEntity entity = securityPatrolEventReportDao.selectOne(
                new LambdaQueryWrapper<SecurityPatrolEventReportEntity>()
                        .eq(SecurityPatrolEventReportEntity::getTaskRouteId, taskRouteId)
                        .eq(SecurityPatrolEventReportEntity::getSubjectId, subjectId)
        );
        return paddingField(CopyUtils.copyObj(entity, SecurityPatrolEventReportDto.class));
    }

    /**
     * 根据taskRouteId 找到巡更上报记录 list
     *
     * @param taskRouteId
     * @return
     */
    @Override
    public List<SecurityPatrolEventReportDto> selectBySecurityPatrolTaskRouteId(Long taskRouteId) {
        List<SecurityPatrolEventReportEntity> entities = securityPatrolEventReportDao.selectList(
                new LambdaQueryWrapper<SecurityPatrolEventReportEntity>()
                        .eq(SecurityPatrolEventReportEntity::getTaskRouteId, taskRouteId));
        List<SecurityPatrolEventReportDto> result = CopyUtils.copyList(entities, SecurityPatrolEventReportDto.class);
        return result;
    }

    @Override
    public SecurityPatrolEventReportDto selectCacheById(Long id) {
        return CacheKit.cacheToRedis(
                () -> selectById(id),
                SECURITY_PATROL_EVENT_REPORT_CACHE_BY_ID_FUNC.apply(id),

                SystemConstants.NOT_NULL_CACHE_EXPIRE_SECONDS
        );
    }

    @Override
    public SecurityPatrolEventReportDto selectById(Long id) {
        SecurityPatrolEventReportEntity entity = securityPatrolEventReportDao.selectById(id);
        return paddingField(CopyUtils.copyObj(entity, SecurityPatrolEventReportDto.class));
    }

    @Override
    public List<SecurityPatrolEventReportDto> queryList(Map<String, Object> params) {
        List<SecurityPatrolEventReportEntity> list = securityPatrolEventReportDao.queryList(params);
        List<SecurityPatrolEventReportDto> result = CopyUtils.copyList(list, SecurityPatrolEventReportDto.class);
        result.forEach(this::paddingField);
        return result;
    }

    private SecurityPatrolEventReportDto paddingField(SecurityPatrolEventReportDto dto) {
        if (dto != null) {
            SecurityPatrolTaskRouteDto taskRouteDto = taskRouteService.selectById(dto.getTaskRouteId());
            if (taskRouteDto.getDeviceId() != null) {
                DeviceDto deviceDto = deviceService.selectByIdWithoutPadding(taskRouteDto.getDeviceId());
                if (deviceDto != null) {
                    dto.setDeviceName(deviceDto.getName());
                    dto.setDeviceDto(deviceDto);
                }
            }
            if (dto.getVillageId() != null) {
                dto.setVillageName(villageService.selectCacheById(dto.getVillageId()).getName());
            }
            if (dto.getWorkOrderId() != null) {
                dto.setWorkOrderDto(workOrderService.selectById(dto.getWorkOrderId()));
                HashMap<String, Object> params = new HashMap<>();
                params.put(LambdaUtil.getFieldName(WorkOrderLogDto::getWorkOrderId), dto.getWorkOrderId());
                dto.setWorkOrderLogDtos(workOrderLogService.queryList(params));
            }
            if (dto.getReportUserId() != null) {
                dto.setReportUserMobile(deptPersonService.selectCacheById(dto.getReportUserId()).getMobile());
            }
            if (dto.getTaskRouteId() != null) {
                dto.setSecurityPatrolTaskRoute(securityPatrolTaskRouteService.selectCacheById(dto.getTaskRouteId()));
            }
        }
        return dto;
    }

    @Override
    public int queryTotal(Map<String, Object> params) {
        return securityPatrolEventReportDao.queryTotal(params);
    }

    @Override
    public Long save(SecurityPatrolEventReportDto dto) {
        SecurityPatrolEventReportEntity entity = CopyUtils.copyObj(dto, SecurityPatrolEventReportEntity.class);
        entity.setId(Snowflake.nextId());
        securityPatrolEventReportDao.insert(entity);
        return entity.getId();
    }

    @Override
    public void updateById(SecurityPatrolEventReportDto dto) {
        SecurityPatrolEventReportEntity entity = CopyUtils.copyObj(dto, SecurityPatrolEventReportEntity.class);
        securityPatrolEventReportDao.updateById(entity);
        CacheKit.invalidRedisCache(SECURITY_PATROL_EVENT_REPORT_CACHE_BY_ID_FUNC.apply(dto.getId()));
    }

    @Override
    public void updateAllColumnById(SecurityPatrolEventReportDto dto) {
        SecurityPatrolEventReportEntity entity = CopyUtils.copyObj(dto, SecurityPatrolEventReportEntity.class);


        MyBatisPlusUtils.updateAllColumnById(entity, securityPatrolEventReportDao);

        CacheKit.invalidRedisCache(SECURITY_PATROL_EVENT_REPORT_CACHE_BY_ID_FUNC.apply(dto.getId()));
    }

    @Override
    public void deleteById(Long id) {
        securityPatrolEventReportDao.deleteById(id);

        CacheKit.invalidRedisCache(SECURITY_PATROL_EVENT_REPORT_CACHE_BY_ID_FUNC.apply(id));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(Long[] ids) {
        for (Long id : ids) {
            deleteById(id);
        }
    }
}
